<template>
  <div class="user-allot-role-box">
    <div class="role-box">
      <span class="title">选择角色</span>
      <div
        v-loading="roleLoading"
        element-loading-text="拼命加载中"
        element-loading-spinner="el-icon-loading"
        element-loading-background="rgba(255, 255, 255, 1)"
        class="content"
      >
        <div class="header-box mb-10">
          <el-checkbox
            v-model="isSelectAll"
            class="mt-10"
            @change="selectAll('roleTreeRef', 'treeList')"
            >全选/全不选</el-checkbox
          >
          <el-checkbox
            v-model="isExpand"
            @change="expandAll('roleTreeRef', 'treeList')"
            >展开/折叠</el-checkbox
          >
        </div>
        <el-tree
          ref="roleTreeRef"
          :data="treeList"
          show-checkbox
          node-key="id"
          :default-expanded-keys="defaultExpandedKeys"
          :default-checked-keys="defaultCheckedKeys"
          :props="defaultProps"
          :check-strictly="true"
          :expand-on-click-node="false"
          highlight-current
          @check="handleCheck"
          @node-click="handleNodeClick"
        />
      </div>
    </div>
    <div class="permiss-box">
      <span class="title">角色权限预览</span>
      <div
        v-loading="permissLoading"
        element-loading-text="拼命加载中"
        element-loading-spinner="el-icon-loading"
        element-loading-background="rgba(255, 255, 255, 1)"
        class="content"
      >
        <el-tree
          ref="permissTreeRef"
          :data="permissList"
          node-key="id"
          :default-expand-all="true"
          :props="{ children: 'children', label: 'menuName' }"
          highlight-current
        />
      </div>
    </div>
    <div class="datalimits-box">
      <span class="title">数据权限预览</span>
      <div class="limits-select">
        <span class="label">权限范围</span>
        <el-select
          v-model="permissionLevelName"
          disabled
          placeholder="权限范围"
          clearable
          :style="{ width: '70%' }"
        >
          <el-option
            v-for="(item, index) in dataLimitsOptions"
            :key="index"
            :label="item.cn"
            :value="item.code"
          />
        </el-select>
      </div>
      <div class="content">
        <div
          v-loading="permissLoading"
          element-loading-text="拼命加载中"
          element-loading-spinner="el-icon-loading"
          element-loading-background="rgba(255, 255, 255, 1)"
          class="content"
        >
          <el-tree
            ref="permissTreeRef"
            :data="deptList"
            node-key="id"
            :default-expand-all="true"
            :props="{ children: 'children', label: 'deptName' }"
            highlight-current
          />
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { arr2tree } from '@/utils'
import { elementMixin } from '@/mixin/element'

export default {
  name: 'UserAllotRole',
  mixins: [elementMixin],
  props: {
    // 弹窗数据
    popData: {
      type: Object,
      default: () => ({})
    },
    // 弹窗取消
    close: {
      type: Boolean,
      default: false
    },
    // 弹窗确认
    confirm: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      roleLoading: false,
      permissLoading: false,
      permissList: [],
      treeList: [],
      activeList: [],
      defaultExpandedKeys: [],
      defaultCheckedKeys: [],
      defaultProps: {
        children: 'children',
        label: 'roleName',
        value: 'id'
      },
      currentNodeKey: '',
      dataLimitsOptions: [],
      dataLimits: '',
      deptList: [],
      permissionLevelName: ''
    }
  },
  watch: {
    confirm() {
      const params = {
        id: this.popData.id,
        roleIds: this.activeList
      }
      this.submit(params)
    }
  },
  created() {},
  mounted() {
    this.getTreeData()
  },
  methods: {
    /**
     * 获取角色数据
     */
    getTreeData() {
      this.roleLoading = true
      const params = {
        id: this.popData.id
      }
      this.$api.userManage
        .queryRole(params)
        .then((res) => {
          if (Number(res.code) === 1000) {
            const { allRoleList = [], ownRoleList = [] } = res.data || {}
            this.treeList = arr2tree(allRoleList, {
              id: 'id',
              parentId: 'parentId'
            })
            const fristItem = this.treeList.find((e, i) => !i) || {}
            this.currentNodeKey = fristItem.id
            this.$nextTick(() => {
              this.$refs.roleTreeRef.setCurrentKey(this.currentNodeKey) // 默认第一个高亮
            })

            this.defaultCheckedKeys = ownRoleList.map((e) => e.id) || []
            this.defaultExpandedKeys = fristItem.id
              ? [fristItem.id, ...this.defaultCheckedKeys]
              : []
            this.activeList = this.defaultCheckedKeys
            this.getPermissionData({ id: fristItem.id })
            this.roleLoading = false
          } else if (res.msg) {
            this.roleLoading = false
          }
        })
        .catch(() => {
          this.roleLoading = false
        })
    },
    /**
     * 获取权限数据
     */
    getPermissionData({ id }) {
      if (!id) return
      this.permissLoading = true
      this.$api.roleManage
        .detail({ id,halfNode: true })
        .then((res) => {
          if (Number(res.code) === 1000) {
            const { ownMenuList = [], ownDeptList = [] } = res.data || {}
            this.permissList = arr2tree(ownMenuList, {
              id: 'menuId',
              parentId: 'parentId'
            })
            console.log('----ownMenuList----> ',this.permissList)
            this.deptList = arr2tree(ownDeptList, {
              id: 'deptId',
              parentId: 'parentId'
            })
            this.permissLoading = false
          } else if (res.msg) {
            this.permissLoading = false
          }
        })
        .catch(() => {
          this.permissLoading = false
        })
    },
    /**
     * 选中
     * @param {*} node 数据
     * @param {*} data 数据
     */
    handleCheck(node, data) {
      // checkedKeys 选中的key
      // halfCheckedKeys 半选的key
      const { checkedKeys } = data || {}
      this.activeList = checkedKeys
    },
    /**
     * 节点点击
     * @param {*} node 数据
     * @param {*} data 数据
     */
    handleNodeClick(node, data) {
      const params = {
        id: node.id
      }
      this.permissionLevelName = node.permissionLevelName
      this.getPermissionData(params)
    },
    /**
     * 提交
     */
    async submit(params) {
      const res = await this.$api.userManage.allotRole(params)
      if (Number(res.code) === 1000) {
        this.$message.success('分配成功!')
        this.$emit('onFinish', 'user-allot-role')
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.user-allot-role-box {
  color: #333;
  padding: 0 20px;
  display: flex;
  justify-content: space-between;
  width: 100%;

  .title {
    color: #333;
    font-size: 18px;
    font-weight: bold;
    height: 40px;
    line-height: 40px;
    padding: 0 20px;
  }

  .role-box {
    width: 30%;
    .content {
      width: 100%;
      height: 50vh;
      overflow: auto;
      border-right: 1px solid #eee;
      padding-right: 10px;
    }
  }

  .permiss-box,
  .datalimits-box {
    width: 30%;
    .content {
      width: 100%;
      height: 45vh;
      overflow: auto;
      margin-top: 4px;
    }
  }

  .permiss-box {
    border-right: 1px solid #eee;
    width: 40%;
  }

  .datalimits-box {
    .content {
      padding-left: 16px;
      color: #606266;
    }
  }

  .limits-select {
    display: flex;
    padding-left: 16px;
    align-items: center;

    .label {
      margin-right: 14px;
    }
  }
}
</style>
